package com.yeswater.multithread.chapter8;

import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * author： yeswater
 * create： 2023/11/9
 */
public class Run_8_2_4 {
    public static void main(String[] args) throws InterruptedException {
        Service service = new Service();
        Thread1 t1 = new Thread1(service);
        Thread1 t2 = new Thread1(service);
        Thread1 t3 = new Thread1(service);
        Thread1 t4 = new Thread1(service);
        Thread1 t5 = new Thread1(service);
        
        t1.start();
        Thread.sleep(1000);
        t2.start();
        Thread.sleep(1000);
        t3.start();
        Thread.sleep(1000);
        t4.start();
        Thread.sleep(1000);
        t5.start();
        Thread.sleep(1000);
    }
    
    public static class Thread1 extends Thread {
        private Service service;
        
        public Thread1(Service service) {
            super();
            this.service = service;
        }
    
        @Override
        public void run() {
            service.testMethod();
        }
    }
    
    public static class Service {
        public ConcurrentSkipListMap<Userinfo, String> map = new ConcurrentSkipListMap<>();
        
        public Service() {
            Userinfo userinfo1 = new Userinfo(1, "userinfo1");
            Userinfo userinfo2 = new Userinfo(2, "userinfo2");
            Userinfo userinfo3 = new Userinfo(3, "userinfo3");
            Userinfo userinfo4 = new Userinfo(4, "userinfo4");
            Userinfo userinfo5 = new Userinfo(5, "userinfo5");
            
            map.put(userinfo1, "u1");
            map.put(userinfo2, "u2");
            map.put(userinfo3, "u3");
            map.put(userinfo4, "u4");
            map.put(userinfo5, "u5");
        }
        
        public void testMethod() {
            Map.Entry<Userinfo, String> entry = map.pollFirstEntry(); //  pollFirstEntry 会将当前的 entry 从 ConcurrentSkipListMap 中删除~
            Userinfo userinfo = entry.getKey();
            System.out.println(userinfo.getId() + " " + userinfo.getUsername() + " " + map.get(userinfo) + " " + entry.getValue());
        }
    }
    
    public static class Userinfo implements Comparable<Userinfo> {
        private int id;
        
        private String username;
        
        public Userinfo(int id, String username) {
            this.id = id;
            this.username = username;
        }
        
        public int getId() {
            return id;
        }
        
        public void setId(int id) {
            this.id = id;
        }
        
        public String getUsername() {
            return username;
        }
        
        public void setUsername(String username) {
            this.username = username;
        }
        
        @Override
        public int compareTo(Userinfo o) {
            if (this.getId() > o.getId()) {
                return 1;
            } else {
                return -1;
            }
        }
    }
}
